package com.kqzz.tbxt.service.impl;

import cn.hutool.core.date.DateUtil;
import com.kqzz.common.api.response.Response;
import com.kqzz.tbxt.bean.*;
import com.kqzz.tbxt.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kqzz.common.service.impl.BaseService;
import com.kqzz.tbxt.service.ICosSysPersonnelService;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description
 * @author lyx
 * @date 2024/10/15
 */
@Service
@Slf4j
public class CosSysPersonnelServiceImpl extends BaseService<CosSysPersonnel> implements ICosSysPersonnelService {

    private final String PORTAL_PERMISSION_DEFAULT = "{\"menu\":[\"manage\",\"overview\",\"server\",\"addServer\",\"monitor\",\"realTimeMonitoring\",\"serviceStatistics\",\"alarmRecord\",\"alarmRules\",\"alarmNotification\",\"resourceManage\",\"serviceManage\",\"serviceManageList\",\"serviceVerify\",\"dataManage\",\"dataManageList\",\"dataVerify\",\"mapManage\",\"mapManageList\",\"mapVerify\",\"scenceManage\",\"scenceManageList\",\"scenceVerify\",\"dashboardManage\",\"dashboardManageList\",\"dashboardVerify\",\"portalStatistics\",\"portalOverview\",\"resourceStatistics\",\"resourceCountStatistics\",\"newResourceStatistics\",\"userStatistics\",\"userCountStatistics\",\"userAddStatistics\",\"accessStatistics\",\"serviceAccessStatistics\",\"dataDownloadStatistics\",\"mapAccessStatistics\",\"scenceAccessStatistics\",\"dashboardAccessStatistics\",\"userSecurity\",\"organizationManage\",\"positionManage\",\"roleManage\",\"permissionManage\",\"userManage\",\"userList\",\"userReview\",\"onlineUser\",\"securityConfig\",\"LDAPLogins\",\"portalConfiguration\",\"site\",\"resourceDefaultThumbnail\",\"resourceCatalog\",\"groupManage\",\"groupManageList\",\"newsManage\",\"newsList\",\"newsClass\",\"log\",\"systemLog\",\"operateLog\",\"logConfig\",\"license\",\"licenseView\"],\"functionAuthority\":{\"resource\":[\"addService\",\"addData\",\"addMap\",\"addScence\",\"addDashboard\",\"addProject\"],\"serviceVerify\":[\"serviceRegister\"],\"dataVerify\":[\"dataRegister\"],\"mapVerify\":[\"mapRegister\"],\"scenceVerify\":[\"scenceRegister\"],\"dashboardVerify\":[\"dashboardRegister\"]}}";
    private final String SERVER_PERMISSION_DEFAULT = "{\"menu\":[\"dataManage\",\"builderModel\",\"serverManagerCluster\",\"manage\",\"organization\",\"monitor\",\"log\",\"backupAndRestore\",\"setUp\",\"siteCustomization\",\"custodyDbConfig\"],\"functionAuthority\":{\"service\":[\"publishService\",\"catalogManage\"]}}";

    @Autowired
    private CosSysPersonnelMapper personnelMapper;

    @Autowired
    private CosSysRolePersonalMapper rolePersonalMapper;

    @Autowired
    private CosSysTenantMapper tenantMapper;

    @Autowired
    private CosSysRoleMapper sysRoleMapper;

    @Autowired
    private CosSysPermissionMapper sysPermissionMapper;

    @Autowired
    private CosSysRolePermissionMapper sysRolePermissionMapper;

    /**
     * 通过token获取填报系统中的用户信息数据
     * @return
     */
    @Override
    @Transactional
    public Response user(HttpServletRequest request) {
        // SSOSessionData currentUser = SSOSessionData.getCurrentUser();
        SSOSessionData currentUser = UserSessionHolder.getCurrentUser();
        String tenantId = currentUser.getRealm();
        String username = currentUser.getUsername();

        //同步用户信息
        //根据loginName和tenantId来判断存不存在（客户的userId不能作为判断条件）
        CosSysPersonnel queryPersonnel = new CosSysPersonnel();
        queryPersonnel.setcTenantId(tenantId);
        queryPersonnel.setcLoginName(username);
        CosSysPersonnel personnel = personnelMapper.selectOne(queryPersonnel);
        log.info("### personnel:{}", personnel);
        if (Objects.isNull(personnel)) {
            CosSysPersonnel sysPersonnel = new CosSysPersonnel();
            sysPersonnel.setcTenantId(tenantId);
            sysPersonnel.setcLoginType(0);
            sysPersonnel.setcName(username);
            sysPersonnel.setcLoginName(username);
            sysPersonnel.setcPassword("a3caed36f0fe5a01e5f144db8927235e"); //密码：123456
            sysPersonnel.setcPasswordPolicy(1);
            sysPersonnel.setcUuid(currentUser.getUserId());
            sysPersonnel.setcDeleted(false);
            sysPersonnel.setcStatus(true);
            sysPersonnel.setcIsverify(1);
            int result = personnelMapper.insertSelective(sysPersonnel);
            log.info("### personnelMapper.insertSelective:{}", result);
        } else {
            personnel.setcLoginName(username);
            personnel.setcName(username);
            int result = personnelMapper.updateByPrimaryKeySelective(personnel);
            log.info("### personnelMapper.updateByPrimaryKeySelective:{}", result);
        }

        //新增portal在该租户下的角色（先判断是否存在，通过clientCode和tenantId两个字段来判断）
        addSysRole("portal", tenantId, "xwrole", "xwrole", "星网角色");

        //新增server在该租户下的角色（先判断是否存在，通过clientCode和tenantId两个字段来判断）
        addSysRole("serverManager", tenantId, "xwserverrole", "xwserverrole", "星网server角色");

        //获取用户id
        CosSysPersonnel p = new CosSysPersonnel();
        p.setcLoginName(username);
        p.setcTenantId(tenantId);
        CosSysPersonnel sysPersonnel = personnelMapper.selectOne(p);  //todo （已改）需要根据loginName和tenantId来判断存不存在（客户的userId不能作为判断条件），来获取用户

        //获取portal角色id,需要使用code、clientCode、tenantId来获取
        CosSysRole sysPortalRole = getCosSysRoleByParam("xwrole", "portal", tenantId);

        //获取server角色id,需要使用code、clientCode、tenantId来获取
        CosSysRole sysServerRole = getCosSysRoleByParam("xwserverrole", "serverManager", tenantId);

        //新增用户角色关联数据
        CosSysRolePersonal sysPortalRolePersonal = new CosSysRolePersonal();
        sysPortalRolePersonal.setcPersonnelId(sysPersonnel.getcId());
        sysPortalRolePersonal.setcRoleId(sysPortalRole.getcId());
        CosSysRolePersonal cosSysRolePersonal = rolePersonalMapper.selectOne(sysPortalRolePersonal);
        if (Objects.isNull(cosSysRolePersonal)) {
            sysPortalRolePersonal.setcDeleted(false);
            sysPortalRolePersonal.setcTenantId(tenantId);
            int result = rolePersonalMapper.insertSelective(sysPortalRolePersonal);
            log.info("### rolePersonalMapper.insertSelective:{}", result);
        }

        CosSysRolePersonal sysServerRolePersonal = new CosSysRolePersonal();
        sysServerRolePersonal.setcPersonnelId(sysPersonnel.getcId());
        sysServerRolePersonal.setcRoleId(sysServerRole.getcId());
        CosSysRolePersonal cosSysRolePersonal1 = rolePersonalMapper.selectOne(sysServerRolePersonal);
        if (Objects.isNull(cosSysRolePersonal1)) {
            sysServerRolePersonal.setcDeleted(false);
            sysServerRolePersonal.setcTenantId(tenantId);
            int result1 = rolePersonalMapper.insertSelective(sysServerRolePersonal);
            log.info("### rolePersonalMapper.insertSelective:{}", result1);
        }

        //新增portal在该租户下的权限（先判断是否存在，通过clientCode和tenantId两个字段来判断）
        addCosSysPermission("portal", tenantId, "xwportaladmin", "xwportaladmin", "星网portal权限");

        //新增server在该租户下的权限（先判断是否存在，通过clientCode和tenantId两个字段来判断）
        addCosSysPermission("serverManager", tenantId, "xwserveradmin", "xwserveradmin", "星网server权限");

        //获取portal权限id,需要使用code、clientCode、tenantId来获取
        CosSysPermission c1 = getCosSysPermission("xwportaladmin", "portal", tenantId);
        //获取server权限id,需要使用code、clientCode、tenantId来获取
        CosSysPermission c2 = getCosSysPermission("xwserveradmin", "serverManager", tenantId);

        //新增角色权限关联数据
        addCosSysRolePermission(c1.getcId(), sysPortalRole.getcId(), tenantId);
        addCosSysRolePermission(c2.getcId(), sysServerRole.getcId(), tenantId);

        //插入租户数据
        CosSysTenant tenant = tenantMapper.queryByCode(currentUser.getAppId());
        if (Objects.isNull(tenant)) {
            CosSysTenant cosSysTenant = new CosSysTenant();
            cosSysTenant.setcCode(currentUser.getAppId());
            cosSysTenant.setcDeleted(false);
            if (StringUtils.isBlank(username)) {
                cosSysTenant.setcName("星网用户");
            } else {
                cosSysTenant.setcName(username);
            }
            int result = tenantMapper.insertSelective(cosSysTenant);
            log.info("### tenantMapper.insertSelective:{}", result);
        }
        return new Response().success(currentUser);
    }

    private void addCosSysRolePermission(Long permissionId, Long roldId, String tenantId) {
        CosSysRolePermission cosSysRolePermission = new CosSysRolePermission();
        cosSysRolePermission.setcPermissionId(permissionId);
        cosSysRolePermission.setcRoleId(roldId);
        cosSysRolePermission.setcTenantId(tenantId);
        CosSysRolePermission result = sysRolePermissionMapper.selectOne(cosSysRolePermission);
        if(Objects.isNull(result)) {
            cosSysRolePermission.setcDeleted(false);
            int result2 = sysRolePermissionMapper.insertSelective(cosSysRolePermission);
            log.info("### sysRolePermissionMapper.insertSelective:{}", result2);
        }
    }

    private CosSysRole getCosSysRoleByParam(String code, String clientCode, String tenantId) {
        CosSysRole cosPortalSysRole = new CosSysRole();
        cosPortalSysRole.setcCode(code);
        cosPortalSysRole.setcClientCode(clientCode);
        cosPortalSysRole.setcTenantId(tenantId);
        return sysRoleMapper.selectOne(cosPortalSysRole);
    }

    private void addCosSysPermission(String clientCode, String tenantId, String code, String name,
                                     String description) {
        CosSysPermission cosSysPermission = new CosSysPermission();
        cosSysPermission.setcClientCode(clientCode);
        cosSysPermission.setcCode(code);
        cosSysPermission.setcTenantId(tenantId);
        CosSysPermission result = sysPermissionMapper.selectOne(cosSysPermission);
        if(Objects.isNull(result)) {
            cosSysPermission.setcStatus(true);
            cosSysPermission.setcDeleted(false);
            cosSysPermission.setcCode(code);
            cosSysPermission.setcName(name);
            cosSysPermission.setcIncludeResourceUrl("portal".equals(clientCode) ? PORTAL_PERMISSION_DEFAULT : SERVER_PERMISSION_DEFAULT);
            cosSysPermission.setcDescribe(description);
            cosSysPermission.setcCreateTime(DateUtil.date());
            cosSysPermission.setcUpdateTime(DateUtil.date());
            int result1 = sysPermissionMapper.insertSelective(cosSysPermission);
            log.info("### sysPermissionMapper.insertSelective:{}", result1);

        }
    }

    private CosSysPermission getCosSysPermission(String code, String clientCode, String tenantId) {
        CosSysPermission cosSysPermission = new CosSysPermission();
        cosSysPermission.setcCode(code);
        cosSysPermission.setcClientCode(clientCode);
        cosSysPermission.setcTenantId(tenantId);
        return sysPermissionMapper.selectOne(cosSysPermission);
    }

    private void addSysRole(String clientCode, String tenantId, String code, String name, String description) {
        CosSysRole querySysRole = new CosSysRole();
        querySysRole.setcClientCode(clientCode);
        querySysRole.setcCode(code);
        querySysRole.setcTenantId(tenantId);
        CosSysRole resultSysRole = sysRoleMapper.selectOne(querySysRole);
        if(Objects.isNull(resultSysRole)) {
            querySysRole.setcStatus(true);
            querySysRole.setcDeleted(false);
            querySysRole.setcCode(code);
            querySysRole.setcName(name);
            querySysRole.setcDescribe(description);
            querySysRole.setcUpdateTime(DateUtil.date());
            querySysRole.setcCreateTime(DateUtil.date());
            int result = sysRoleMapper.insertSelective(querySysRole);
            log.info("### sysRoleMapper.insertSelective:{}", result);
        }
    }
}
